package com.km.app.controller.param;

import com.km.app.util.ImageTools;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;

public class ResizeAndCropState implements ParamState {
    private final static Log log = LogFactory.getLog(CropState.class);
    private Integer width;
    private Integer height;
    private String srcPath;
    private String targetPath;

    public ResizeAndCropState(String srcPath) {
        this.srcPath = srcPath == null ? null : srcPath.trim();
    }

    /**
     * 切割并摍放图片
     *
     * @param width      原图片高
     * @param height     原图片宽
     * @param maxWidth   期待宽
     * @param maxHeight  期待高
     * @param srcPath    原图片地址
     * @param targetPath 生成图片地址
     * @throws Exception
     */
    public void cropAndResizeImage(String srcPath, String targetPath, int width, int height, int maxWidth,
                                   int maxHeight)
            throws Exception {
        BigDecimal w = new BigDecimal(width); // 原始宽度
        BigDecimal h = new BigDecimal(height);// 原始高度
        BigDecimal mw = new BigDecimal(maxWidth);// 期待宽度
        BigDecimal mh = new BigDecimal(maxHeight);// 期待高度
        BigDecimal cuth = null;// 要切割的高
        BigDecimal cutw = null;// 要切割的宽
        int[] x = {0, width}; // x坐标范围
        int[] y = {0, height};// y坐标范围
        // 确定切隔参照边
        if (w.divide(mw, 5, BigDecimal.ROUND_DOWN).compareTo(
                h.divide(mh, 5, BigDecimal.ROUND_DOWN)) < 1) {
            cuth = w.multiply(mh).divide(mw, 5, BigDecimal.ROUND_DOWN); // 切割高
        } else {
            cutw = mw.divide(mh, 5, BigDecimal.ROUND_DOWN).multiply(h);// 切割宽
        }
        if (cuth != null) {
            // 计算y坐标
            y[0] = h.subtract(cuth)
                    .divide(new BigDecimal(2), 5, BigDecimal.ROUND_DOWN)
                    .setScale(0, BigDecimal.ROUND_DOWN).intValue();
            y[1] = height - y[0];
        }
        if (cutw != null) {
            // 计算x坐标
            x[0] = w.subtract(cutw)
                    .divide(new BigDecimal(2), 5, BigDecimal.ROUND_DOWN)
                    .setScale(0, BigDecimal.ROUND_DOWN).intValue();
            x[1] = width - x[0];
        }
        String path = srcPath.substring(0, srcPath.lastIndexOf("."));
        String suffix = srcPath.substring(srcPath.lastIndexOf("."));
        String cutFullPath = path + "_cutTemp_" + suffix;
        ImageTools.corpImageByCoordinate(srcPath, cutFullPath, x[0], y[0], x[1],
                y[1]);
        ImageTools.resizeImage(cutFullPath, targetPath, maxWidth, maxHeight);
        File fp = new File(cutFullPath);
        if (fp.exists()) {
            fp.delete();
        }
    }

    @Override
    public File action(ParamContext context) {
        String[] var1 = context.getQuery().split(",");
        if (var1 == null || var1.length == 0) {
            return null;
        }
        if (this.srcPath == null || this.srcPath.length() == 0) {
            return null;
        }
        for (String var2 : var1) {
            if (var2 == null || var2.trim().length() == 0) {
                continue;
            }
            String[] var3 = var2.split("_");
            if (var3 != null && var3.length == 2) {
                if (var3[0].equals("width")) {
                    this.width = Integer.valueOf(var3[1]);
                }
                if (var3[0].equals("height")) {
                    this.height = Integer.valueOf(var3[1]);
                }
            }
        }
        if (this.width == null && this.height == null) {
            return null;
        }
        String var4 = this.srcPath.substring(0, this.srcPath.lastIndexOf("."));
        String var5 = this.srcPath.substring(this.srcPath.lastIndexOf("."));
        this.targetPath = var4 + "_cropAndResize_" + (this.width != null ? this.width : "0") + "x" + (this.height != null ? this.height : "0");
        if (var5 != null) {
            targetPath +=  var5;
        }
        File f = new File(targetPath);
        if (f.exists()) {
            return f;
        }
        try {
            // 缓存图片读取宽和高
            BufferedImage image = ImageIO.read(new FileInputStream(this.srcPath));
            int width = image.getWidth();
            int height = image.getHeight();
            this.cropAndResizeImage(this.srcPath, this.targetPath, width, height, this.width, this.height);
            return new File(this.targetPath);
        } catch (Exception e) {
            log.error(e);
            return null;
        }
    }
}
